package com.sq.goodline.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sq.goodline.config.ApiConfig;
import com.sq.goodline.controller.dto.AccessTokenDto;
import com.sq.goodline.controller.dto.AxbRequestDto;
import com.sq.goodline.controller.dto.AxbResultDto;
import com.sq.goodline.controller.dto.DeleteAxbDto;
import com.sq.goodline.controller.dto.ResultDto;
import com.sq.goodline.controller.dto.TransResponse;
import com.sq.goodline.dao.AxbBindDao;
import com.sq.goodline.dao.PartnerNumxDao;
import com.sq.goodline.dao.po.PartnerAxbBinding;
import com.sq.goodline.dao.po.PartnerNumx;
import com.sq.goodline.dao.po.PartnerToken;
import com.sq.goodline.util.Constants;
import com.sq.goodline.util.ContextUtil;
import com.sq.goodline.util.DateUtils;
import com.sq.goodline.util.HttpUtils;
import com.sq.goodline.util.http.HttpClientUtil;
import com.sq.goodline.util.http.HttpRequest;
import com.sq.goodline.util.http.HttpResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AxbService {
	
	@Autowired
	ApiConfig apiConfig;
	@Autowired
	HttpClientUtil httpClientUtil;
	@Autowired
	PartnerNumxDao partnerNumxDao;
	@Autowired
	AxbBindDao axbBindDao;
	
	
	/**
	 * axb绑定
	 * @param axbRequest
	 * @return
	 */
	public TransResponse<List<AxbResultDto>> axbInsert(List<AxbRequestDto> requestDtoList) {
		try {
			if(requestDtoList==null || requestDtoList.size()==0 ||requestDtoList.size()>10) {
				return TransResponse.error("参数不符合规范");
			}
			
			if(numxCheck(requestDtoList)){//x号码检查
				return TransResponse.error("x号码权限校验不通过");
			}
			
			String result = HttpUtils.doGet(apiConfig.getAccessTokenUrl());
			log.info("获取token响应报文：{}",result);
			
			if(StringUtils.isBlank(result)) {
				return TransResponse.error("axb绑定获取token失败,请稍后再试");
			}else {
				AccessTokenDto tokenDto = JSON.parseObject(result, AccessTokenDto.class);
				String token = tokenDto.getResult().getAccess_token();
				String url ="http://223.255.252.183:30001/gw/bind/insert/binding/insertWorkAXB?access_token="+token;
				
				String jsonStr = JSON.toJSONString(requestDtoList);
						
				HttpRequest httpRequest = new HttpRequest();
				Map<String, String> headMap = new HashMap<>();
				headMap.put("x-request-id", UUID.randomUUID().toString().replace("-",""));
				headMap.put("Connection", "keep-alive");
				headMap.put("Content-Type", "application/json");
				httpRequest.setHeadMap(headMap);
				httpRequest.setRequestBody(jsonStr);
				httpRequest.setUrl(url);
				
				log.info("axb绑定http请求信息：{}",JSON.toJSONString(httpRequest));
				HttpResult httpResult = httpClientUtil.doHttpPost(httpRequest);
				
				if(200!=httpResult.getStatusCode()){
					log.error("axb绑定失败，状态码：{}",httpResult.getStatusCode());
					return TransResponse.error("axb绑定失败,请稍后再试");
				}else {
					String responseJson = httpResult.getContent();
					log.info("axb绑定响应报文：{}",responseJson);
					ResultDto<JSONArray> resultDto = JSON.parseObject(responseJson, ResultDto.class);
					List<AxbResultDto> bindedList = JSONArray.parseArray(resultDto.getResBody().toString(),AxbResultDto.class);
					//插入数据库
					insertAxb(bindedList);
					return TransResponse.success(bindedList);
				}
			}
		}catch(Exception e) {
			log.error("axb绑定异常：",e);
			return TransResponse.error("axb绑定异常");
		}
	}
    
	/**
	 * 检查x号码是否归属于合作方
	 * @param requestDtoList
	 * @return
	 */
	private boolean numxCheck(List<AxbRequestDto> requestDtoList) {
		PartnerToken pt = ContextUtil.getThreadContext(Constants.CURRENT_TOKEN,PartnerToken.class);
		for(AxbRequestDto dto:requestDtoList) {
			PartnerNumx numx = partnerNumxDao.selectById(dto.getCallNumX());
			if(!pt.getPartnerCode().equalsIgnoreCase(numx.getPartnerCode())) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * axb入库
	 * @param bindedList
	 */
	private void insertAxb(List<AxbResultDto> bindedList) {
		for(AxbResultDto resultDto:bindedList) {
			PartnerAxbBinding po = new PartnerAxbBinding();
			po.setBindId(resultDto.getBindId());
			po.setCallNumA(resultDto.getCallNumA());
			po.setCallNumX(resultDto.getCallNumX());
			po.setCallNumB(resultDto.getCallNumB());
			po.setEffectStartTime(DateUtils.formatTime(resultDto.getEffectStartTime()));
			po.setEffectEndTime(DateUtils.formatTime(resultDto.getEffectEndTime()));
			po.setBindStatus(1);
			int a = axbBindDao.insert(po);
			log.info("插入axb绑定关系完成：",a);
		}
	}
	
	/**
	 * axb解绑
	 * @param deleteAxbRequest
	 * @return
	 */
	public TransResponse<Object> axbDelete(List<DeleteAxbDto> deleteAxbRequest) {
//		List<DeleteAxbDto> deleAxbDtoList = deleteAxbRequest.getRequestBody();
//		for(DeleteAxbDto deleAxbDto : deleAxbDtoList) {
//			AxbBinding po = axbBindDao.selectById(deleAxbDto.getBindId());
//		}
		
    	return null;
	}
}
